#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
static bool DEBUG=false;

#define LOCKFILE "/var/run/tuduyet.pid"
#define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)



int sleep_time = 900;

const int max_proxy=100;
string proxies[max_proxy];
string useragent[6];
string urls[5];
int id=0;
//For daemon start:
static bool STOP=false;
void call_for_exit(int s)
{
   STOP=true;
   printf("Stopping tuduyet...\n");
}

void write_log(const char *fmt, ...)
{
	va_list         ap;
	char            buffer[4096];
	char times[20];
    struct tm *sTm;
    time_t now = time (0);
    sTm = gmtime (&now);
    strftime (times, sizeof(times), "%Y-%m-%d %H:%M:%S", sTm);

	sprintf(buffer,"/var/log/tuduyet.log");
	FILE *fp = fopen(buffer, "a+");
	if (fp==NULL)
    {
		 fprintf(stderr,"openfile error!\n");
		 system("pwd");
	}va_start(ap, fmt);
	vsprintf(buffer, fmt, ap);
	fprintf(fp,"%s \t %s\n",times,buffer);
	//if (DEBUG) printf("%s\n",buffer);
	va_end(ap);
	fclose(fp);

}


//Xu li chinh

//For daemon:
int lockfile(int fd)
{
	struct flock fl;
	fl.l_type = F_WRLCK;
	fl.l_start = 0;
	fl.l_whence = SEEK_SET;
	fl.l_len = 0;
	return (fcntl(fd,F_SETLK,&fl));
}
bool already_running()
{
	int fd;
	char buf[16];
	fd = open(LOCKFILE, O_RDWR|O_CREAT, LOCKMODE);
	if (fd < 0)
    {
		write_log("can't open %s: %s", LOCKFILE, strerror(errno));
		return true;
	}
	if (lockfile(fd) < 0)
    {
		if (errno == EACCES || errno == EAGAIN)
		{
			close(fd);
			return true;
		}
		write_log("can't lock %s: %s", LOCKFILE, strerror(errno));
		return true;
	}
	ftruncate(fd, 0);
	sprintf(buf,"%d", getpid());
	write(fd,buf,strlen(buf)+1);
	return false;
}
bool daemon_init(void)
 {
     setsid();
     umask(0); /* clear file mode creation mask */
     close(0); /* close stdin */
     close(1); /* close stdout */
     close(2); /* close stderr */
     return(true);
}
void getProxyList()
{
	string line;
	ifstream myFile("/etc/proxy.txt");
	if(!myFile.good())
	{
		cout << "Error opening file proxy.txt"<<endl;
		return ;
	}
    id=0;
	while(!myFile.eof())
	{
		getline(myFile, line);
		proxies[id]=line;
		id++;
		if (id>=max_proxy) break;
	}
	id--;
	myFile.close();
    if (DEBUG)
        write_log("Get total %d proxies",id);
}
void getUrlList()
{
    FILE *stream;
    int MAX_BUFFER = 1000;
    char buffer[MAX_BUFFER];
    stream = popen("tail -n 5 /var/log/duyetweb.log", "r");
    int i=0;
    while ( fgets(buffer, MAX_BUFFER, stream) != NULL )
    {
        if (strlen(buffer)>10)
        {
            urls[i]=string(buffer);
        }
        i++;
    }
    pclose(stream);
}
void curl_proxy(const char * url)
{
    char cmd[500];
    int i=0;
    int a;
    while (i<id)
    {
        a=rand() % 6;
        if (DEBUG)
        {
            sprintf(cmd,"curl -A \"%s\" -x %s %s >/dev/null",useragent[a].c_str(),proxies[i].c_str(),url);
        }
        else
        {
            sprintf(cmd,"curl -A \"%s\" -s -x %s %s >/dev/null",useragent[a].c_str(),proxies[i].c_str(),url);
        }
        //cout<<i<<". CURL: "<<cmd<<endl;
        //write_log("%d# %s",i,cmd);
        system(cmd);
        //sleep(1);
        i++;
    }

}
int main(int argc, char** argv)
{
	if (argc>1) DEBUG=true;
    if (!DEBUG) daemon_init();
    if (already_running())
    {
        write_log("tuduyet is already running!");
        return 1;
    }
    signal(SIGQUIT,call_for_exit);
	signal(SIGKILL,call_for_exit);
	signal(SIGTERM,call_for_exit);
	useragent[0]=string("Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
    useragent[1]=string("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30");
    useragent[2]=string("Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0");
    useragent[3]=string("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0");
    useragent[4]=string("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
    useragent[5]=string("Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)");
    int i=0;
    while (!STOP)
    {
		getProxyList();
		getUrlList();
		for (i=0;i<5;i++)
        {
            curl_proxy(urls[i].c_str());
        }

        sleep(sleep_time);
    }

    return 0;
}
